<script setup lang="tsx">
import { reactive, ref, unref, markRaw, shallowRef, provide, type Component } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import Details from './component/Details.vue'
import { ElCollapseTransition } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import {
  getListApi,
  delUserApi,
  getSelectListApi,
  modifyUserApi,
  type Row
} from '@/api/system/staff'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

const exportToExcel = async () => {
  const res = await getListApi({
    page: 1,
    limit: 10,
    is_export: 1
  })
  const list = res.data.list.map((res) => {
    return {
      订单号: res.no,
      下单时间: res.create_time,
      客户名称: res.real_name,
      累计数量: res.quantity,
      累计金额: res.amount
    }
  })
  // 将数据转换为工作表
  const ws = XLSX.utils.json_to_sheet(list)
  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  // 生成 Excel 文件并保存
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '订单列表.xlsx')
}

defineOptions({
  name: 'Role'
})
const comId = reactive({
  Details: markRaw(Details)
})
const searchRef = ref()
const projectSelectLoading = ref(false)
const projectSelectOptions = ref([])
const searchProject = async (query) => {
  if (query) {
    searchRef.value?.setSchema([
      {
        field: 'user_id',
        path: 'componentProps.loading',
        value: true
      }
    ])
    const res = await getSelectListApi(query)
    if (res) {
      searchRef.value?.setSchema([
        {
          field: 'user_id',
          path: 'componentProps.options',
          value: res.data.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      ])
    }
    searchRef.value?.setSchema([
      {
        field: 'user_id',
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: 'selection' }
  },
  {
    field: 'no',
    label: '订单号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'create_time',
    label: '下单时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD'
      }
    },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'real_name',
    label: '客户名称',
    search: {
      field: 'user_id',
      component: 'Select',
      componentProps: {
        placeholder: '支持模糊搜索',
        filterable: true,
        remote: true,
        loading: projectSelectLoading.value,
        remoteMethod: searchProject,
        options: projectSelectOptions.value
      }
    },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'quantity',
    label: '累计数量',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'amount',
    label: '累计金额',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      slots: {
        default: ({ row }) => {
          return (
            <>
              <BaseButton type="primary" onClick={async () => await detailsAction(row.id)}>
                详情
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const tableData = ref([] as any)
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    tableData.value = res.data.list
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delUserApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const showCollapse = ref(false)
let currentAction = shallowRef()
let currentRow = ref<Row | undefined>(undefined)
const action = (component: Component, row?: Row) => {
  currentAction.value = component
  currentRow.value = row
  if (showCollapse.value === false) showCollapse.value = true
}
// 详情
const detailsAction = async (id: string) => {
  const res = await modifyUserApi({ id })
  // 请求 await
  // 赋值 currentRow
  action(comId['Details'], res.data.order)
}
const closeCollapse = () => {
  showCollapse.value = false
}
const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton>
      <BaseButton :loading="delLoading" type="primary" @click="exportToExcel()">导出 </BaseButton>
    </div>

    <el-collapse-transition>
      <component
        :is="currentAction"
        @close="closeCollapse"
        @get-list="getList"
        v-show="showCollapse"
      />
    </el-collapse-transition>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
